import org.junit.Before;
import org.junit.Test;

import java.sql.*;

public class 哲哲 {

        Connection connection=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        String sql = "";

        @Before
        public void init() throws ClassNotFoundException, SQLException {
            //连接驱动
            Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");
            //获得到连接对象
            connection = DriverManager.getConnection("jdbc:phoenix:master:2181");
        }


        /**
         * 查询
         * @throws ClassNotFoundException
         * @throws SQLException
         */
        @Test
        public void query() throws SQLException {
            sql = "select * from users";
            //根据连接对象获得发送器
            ps = connection.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString("NAME"));
            }

            ps.close();
            connection.close();
        }


        /**
         * 创建表
         * @throws SQLException
         */
        @Test
        public void createTable() throws SQLException {
            sql = "create table if not exists t_person(id integer not null primary key,name varchar(20),age integer)";
            ps = connection.prepareStatement(sql);
            ps.execute();
            System.out.println("runnning:"+sql);
            ps.close();
            connection.close();
        }


        /**
         * 添加数据
         * @throws SQLException
         */
        @Test
        public void add() throws SQLException {
            sql = "upsert into t_person select * from users where age > 13";
            ps = connection.prepareStatement(sql);
            int i = ps.executeUpdate();
            connection.commit();
            System.out.println("running:"+i+"行");
            ps.close();
            connection.close();
        }


        /**
         * 删除数据
         * @throws SQLException
         */
        @Test
        public void delete() throws SQLException {
            sql = "delete from t_person where age=16";
            ps = connection.prepareStatement(sql);
            int i = ps.executeUpdate();
            connection.commit();
            System.out.println("running:"+i+"行");
            ps.close();
            connection.close();
        }


        /**
         * 更新数据
         * @throws SQLException
         */
        @Test
        public void update() throws SQLException {
            sql = "upsert into t_person (id,name) values (?,?)";
            ps = connection.prepareStatement(sql);

            ps.setInt(1,1);
            ps.setString(2,"up");

            int i = ps.executeUpdate();
            connection.commit();
            System.out.println("running:"+i+"行");
            ps.close();
            connection.close();
        }
    }



